import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import classification_report, accuracy_score
from sklearn.svm import SVC
from sklearn.externals import joblib

class Classification:
    def __init__(self):
        self.df = pd.read_csv('fina_indicator.csv')

    def get_conditions(self):
        # 分点标准
        df = self.df
        # 计算风险和回报比例
        df['max_ratio'] = df['max_close'] / df['the_close']  # 收益潜力
        df['min_ratio'] = df['min_close'] / df['the_close']  # 风险潜力

        # 给比例分阈值
        high_return_threshold = df['max_ratio'].quantile(0.6)  # 前40%定义为高收益
        high_risk_threshold = df['min_ratio'].quantile(0.4)  # 前40%定义为高风险

        # 生成分类标签
        conditions = [
            (df['max_ratio'] >= high_return_threshold) & (df['min_ratio'] >= high_risk_threshold),
            (df['max_ratio'] >= high_return_threshold) & (df['min_ratio'] < high_risk_threshold),
            (df['max_ratio'] < high_return_threshold) & (df['min_ratio'] >= high_risk_threshold),
            (df['max_ratio'] < high_return_threshold) & (df['min_ratio'] < high_risk_threshold)
        ]
        choices = ["高收益高风险", "低收益高风险", "高收益低风险", "低收益低风险"]
        df['Category'] = np.select(conditions, choices, default="未知")

        # 特征选择
        features = df[['eps', 'total_revenue_ps', 'undist_profit_ps', 'gross_margin', 'fcff', 'fcfe', 'tangible_asset', 'bps', 'grossprofit_margin', 'npta']]

        # 标签编码
        label_encoder = LabelEncoder()
        df['Category_encoded'] = label_encoder.fit_transform(df['Category'])

        # 数据标准化
        scaler = StandardScaler()
        X = scaler.fit_transform(features)
        y = df['Category_encoded']
        # 划分训练集和测试集
        X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
        # 保存scaler
        dump(scaler, 'scaler.pkl')
        return X_train, X_test, y_train, y_test, label_encoder

    def knn_util(self, X_train, X_test, y_train, y_test, label_encoder):
        # KNN分类器
        knn = KNeighborsClassifier(n_neighbors=3)
        knn.fit(X_train, y_train)
        y_pred_knn = knn.predict(X_test)
        print(classification_report(y_test, y_pred_knn, target_names=label_encoder.classes_))
        dump(knn, 'knn_model.joblib')
        dump(label_encoder, 'label_encoder.joblib')

    def svm_util(self, X_train, X_test, y_train, y_test, label_encoder):
        # SVM分类器
        svm = SVC(kernel='linear', C=1.0, random_state=42)
        svm.fit(X_train, y_train)
        y_pred_svm = svm.predict(X_test)
        print(classification_report(y_test, y_pred_svm, target_names=label_encoder.classes_))
        dump(svm,'svm_model.joblib')
        dump(label_encoder, 'label_encoder.joblib')

if __name__ == '__main__':
    ci = Classification()
    X_train, X_test, y_train, y_test, label_encoder = ci.get_conditions()
    # ci.knn_util(X_train, X_test, y_train, y_test, label_encoder)
    ci.svm_util(X_train, X_test, y_train, y_test, label_encoder)